package com.ikkong.biz.service.impl;

import com.fj.hiwetoptools.PinyinUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.ikkong.biz.BizCst;
import com.ikkong.biz.excel.TeacherOfMode;
import com.ikkong.core.toolbox.ExcelStatistic;
import com.ikkong.common.vo.User;
import com.ikkong.core.base.service.impl.BaseService;
import com.ikkong.biz.model.AsyncWeixin;
import com.ikkong.biz.model.Teacher;
import com.ikkong.biz.service.AsyncWeixinService;
import com.ikkong.biz.service.AsyncWeixinService.OPTYPE;
import com.ikkong.biz.service.TeacherService;
import com.ikkong.core.dao.Blade;
import com.ikkong.core.dao.Db;
import com.ikkong.core.exception.BizException;
import com.ikkong.core.jfinal.ext.kit.JStrKit;
import com.ikkong.core.jfinal.ext.shiro.ShiroKit;
import com.ikkong.core.toolbox.Conver;
import com.ikkong.core.toolbox.Record;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;

import org.apache.commons.io.IOUtils;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.result.ExcelImportResult;
import org.jeecgframework.poi.exception.excel.ExcelImportException;
import org.jeecgframework.poi.util.PoiPublicUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Generated by Blade. 2016-11-16 10:38:28
 */
public class TeacherServiceImpl extends BaseService<Teacher> implements
		TeacherService {
	private static final String filePath = "excel" + File.separator + "teacher"
			+ File.separator + "teacher_import.xlsx";
	private AsyncWeixinService asyncService = new AsyncWeixinServiceImpl();

	@Override
	public String doImport(File file) throws BizException {
		PropKit.use("config.properties");
        String realpath = PathKit.getWebRootPath() + File.separator
                + filePath;
        try (FileOutputStream fos= new FileOutputStream(realpath)){
            ImportParams params = new ImportParams();
            params.setNeedVerfiy(true);
            ExcelImportResult<TeacherOfMode> result = ExcelImportUtil
					.importExcelVerify(file, TeacherOfMode.class, params);
			result.getWorkbook().write(fos);

			// 插入老师表
			List<Teacher> clss = Lists.newArrayList();
			List<User> users = Lists.newArrayList();

			// TODO 正式的时候改为从10000开始自增
			int count = 10000;
			Integer max = Db.init().queryInt("select max(id) from tb_teacher",
					null);
			if (null != max) {
				count = max.intValue() + 1;
			}
			for (TeacherOfMode cm : result.getList()) {
				if (StrKit.isBlank(cm.getErrorMsg())) {
					cm.setId(count);
					cm.setFirst_spell(PinyinUtil.getPinyinFirst(cm.getName()
							.substring(0, 1)));
					clss.add(cm);
					// 加入用户
					User user = new User();
					user.setAccount(cm.getMobile());
					user.setPhone(cm.getMobile());
					// TODO 设置初始角色
					user.setRoleid(PropKit.get("config.defaultRole"));
					String salt = ShiroKit.getRandomSalt(5);
					String pwd = PropKit.get("config.defaultPwd", "123456");
					String pwdMd5 = ShiroKit.md5(pwd, salt);
					user.setPassword(pwdMd5);
					user.setSalt(salt);
					user.setTeacher_id(count);
					user.setStatus(1);
					user.setCreatetime(new Date());
					user.setName(cm.getName());
					user.setDeptid(BizCst.TEA_TOP_DEPT);
					users.add(user);
					count = count + 1;
				}
			}
			// Blade.dao().executeUpdate(new
			// SQLReady("truncate table tb_teacher"));
			Blade.dao().insertBatch(Teacher.class, clss);

			Blade.dao().insertBatch(User.class, users);

			String reson = ExcelStatistic.statistic(result.getList().size(),
					clss.size(), filePath);
			return reson;
		} catch (Exception e) {
            if (e instanceof ExcelImportException){
                throw new BizException(e.getMessage(),e);
            }
            throw new BizException("导入失败",e);
		} finally {
            file.delete();
		}
	}

	@Override
	public boolean chooseDept(int id, String depts) {
		StringBuilder sb = new StringBuilder(",");
		sb.append(depts).append(",");
		if (id > 0) {
			Teacher teacher = this.findById(id);
			if (teacher != null) {
				teacher.setDepts(sb.toString());
				teacher.setVersion(Conver.toInt(teacher.getVersion(), 0) + 1);
				teacher.setUtime(new Date());
				return this.update(teacher);
			}
		}
		return false;
	}

	public List<Record> noticeTeacherTree(Integer teacherId) {
		List<Map> list = Db.init().queryListMap("SELECT t1.id,t1.NAME,t1.depts from tb_teacher t1,tb_auth_tag at,tb_teacher t2 where t2.id ="
								+ teacherId
								+ " and t2.notice_tag_id = at.id and at.teacher_auth like concat('%,',t1.id,',%') group by t1.id order by t1.id asc");
		List<Record> maps = new ArrayList<>();
		for (Map m : list) {
			String depts = m.get("depts") != null ? m.get("depts").toString()
					: null;
			if (JStrKit.notBlank(depts)) { // 存在部门，拆分depts ,12,12,11,记录为三条
				String[] ss = depts.split(",");
				for (String s : ss) {
					if (StrKit.notBlank(s)) {
						Map map = Maps.newHashMap();
						map.put("id", m.get("id"));
						map.put("pId", Conver.toInt(s, null));
						map.put("name", m.get("name"));
						map.put("leaf", true);
						maps.add(Record.parse(map));
					}
				}
			} else { // 未分配部门的全部挂在顶级节点下面
				Map map = Maps.newHashMap();
				map.put("id", m.get("id"));
				map.put("pId", 1003);
				map.put("name", m.get("name"));
				map.put("leaf", true);
				maps.add(Record.parse(map));
			}
		}
		return maps;
	}
	
	public List<Record> teacherTree() {
		List<Map> list = Db.init().queryListMap(
				Blade.dao().getScript("Teacher.teacherTree").getSql());
		List<Record> maps = new ArrayList<>();
		for (Map m : list) {
			String depts = m.get("depts") != null ? m.get("depts").toString()
					: null;
			if (JStrKit.notBlank(depts)) { // 存在部门，拆分depts ,12,12,11,记录为三条
				String[] ss = depts.split(",");
				for (String s : ss) {
					if (StrKit.notBlank(s)) {
						Map map = Maps.newHashMap();
						map.put("id", m.get("id"));
						map.put("pId", Conver.toInt(s, null));
						map.put("name", m.get("name"));
						map.put("leaf", true);
						maps.add(Record.parse(map));
					}
				}
			} else { // 未分配部门的全部挂在顶级节点下面
				Map map = Maps.newHashMap();
				map.put("id", m.get("id"));
				map.put("pId", 1003);
				map.put("name", m.get("name"));
				map.put("leaf", true);
				maps.add(Record.parse(map));
			}
		}
		return maps;
	}

	@Override
	public String getSubjectTeacherNames(String teachers) {
		if (JStrKit.isBlank(teachers)) {
			return "";
		}

		Map map = Maps.newHashMap();
		List<Integer> list = Lists.newArrayList();
		teachers = JStrKit.removeWrapWithDelimiter(teachers);
		map.put("subjectTeacherIds", teachers.split(","));
		return Db.init().queryStr(
				Db.init().getSql("Teacher.subjectTeacherNames"), map);
	}

	@Override
	public String getHeadTeacherName(Object id) {
		Teacher headTeacher = this.findById(id);
		return headTeacher == null ? "" : headTeacher.getName();
	}

	@Override
	public boolean saveWithUser(Teacher cm) {
		try {
			
			cm.setDepts(JStrKit.wrapWithDelimiter(cm.getDepts(), ","));
			int count = 10000;
			Integer max = Db.init().queryInt("select max(id) from tb_teacher",
					null);
			if (null != max) {
				count = max.intValue() + 1;
			}
			// 加入用户
			User user = new User();
			user.setAccount(cm.getMobile());
			user.setPhone(cm.getMobile());
			// TODO 设置初始角色
			user.setRoleid(PropKit.get("config.defaultRole"));
			String salt = ShiroKit.getRandomSalt(5);
			String pwd = PropKit.get("config.defaultPwd", "123456");
			String pwdMd5 = ShiroKit.md5(pwd, salt);
			user.setPassword(pwdMd5);
			user.setSalt(salt);
			user.setStatus(1);
			user.setName(cm.getName());
			user.setTeacher_id(count);
			user.setVersion(0);
			user.setDeptid(1);
			user.setCreatetime(new Date());
			user.setDeptid(BizCst.TEA_TOP_DEPT);
			Blade.create(User.class).save(user);
			cm.setId(count);
			return this.save(cm);
		} catch (Exception e) {
			LogKit.error(e.getMessage(), e);
			throw new BizException("新增失败", e);
		}
	}

}
